﻿/**
 *  字符结束
 */
String.prototype.endWith = function (s) {
    if (s == null || s == "" || this.length == 0 || s.length > this.length)
        return false;
    return this.substring(this.length - s.length) == s;
};

/**
 *  字符开始
 */
String.prototype.startWith = function (s) {
    if (s == null || s == "" || this.length == 0 || s.length > this.length)
        return false;
    return this.substr(0, s.length) == s;
};

// /**
//  * js 已支持该方法 
//  * @returns 
//  */
// String.prototype.replaceAll = function (str, replaceWith) {
//     var _newStr = this;
//     while (_newStr.indexOf(str) >= 0) {
//        _newStr = _newStr.replace(str, replaceWith)
//     } 
//     return _newStr;
// };
/**
 * 
 * @param {*} regular 正则表达式
 * @param {*} replaceWith 
 * @param {*} ignoreCase 
 * @returns 
 */
 String.prototype.replaceByRegExp = function (regular , replaceWith, ignoreCase) {
    if (!RegExp.prototype.isPrototypeOf(regular)) {
        return this.replace(new RegExp(regular, (ignoreCase ? "gi" : "g")), replaceWith);
    } else {
        return this.replace(regular, replaceWith);
    }
};

/**
 * 
 * */
String.prototype.format = function format(args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    var reg = new RegExp("({[" + i + "]})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
};
/**
 * 首字母大写
 */
String.prototype.toFirstUpperCase = function toFirstUpperCase()
{
    return this.slice(0,1).toUpperCase() + this.slice(1);
};
/**
 * 首字母小写
 */
String.prototype.toFirstLowerCase = function toFirstLowerCase()
{
    return this.slice(0,1).toLowerCase() + this.slice(1);
};
/**
 * @description 删除左边的空格
 */
String.prototype.ltrim = function () {
    return this.replace(/(^\s*)/g, '');
};
/**
 * @description 删除右边的空格
 */
String.prototype.rtrim = function () {
    return this.replace(/(\s*$)/g, '');
};
//数组类型 不允许定义 扩展方法
// /**
//  * @description 清除所有元素
//  */
// Array.prototype.clear = function () {
//     this.length = 0;
//     return this;
// };
// /**
//  * @description 指定位置插入元素
//  * @param {*} index 
//  * @param {*} item 
//  */
// Array.prototype.insertAt = function (index, item) {
//     console.trace(item);
//     this.splice(index, 0, item);
//     return this;
// };
// /**
//  * @description 指定位置移除元素
//  * @param {*} index 
//  */
// Array.prototype.removeAt = function (index) {
//     this.splice(index, 1);
//     return this;
// };
// /**
//  * @description 移除一个元素
//  * @param {*} item 
//  */
// Array.prototype.remove = function (item) {
//     var index = this.indexOf(item);
//     if (index >= 0) {
//         this.removeAt(index);
//     }
//     return this;
// };
/**
 * @description 值有效性判断
 * */
Date.prototype.isValid =function isValid( ) {
    return !(this == 'Invalid Date');
};

/**
*
* @description 格式：yyyy-MM-dd
* */
Date.prototype.format = function format(fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时 ，12
        "H+": this.getHours(),                   //小时 ，24
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };

    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

/*
*
* */
Date.prototype.getWeek = function getWeek() {
    var result;
    var now = new Date();
    var day;
    switch (now.getDay()) {
        case 0:
            day = "日";
            break;
        case 1:
            day = "一";
            break;
        case 2:
            day = "二";
            break;
        case 3:
            day = "三";
            break;
        case 4:
            day = "四";
            break;
        case 5:
            day = "五";
            break;
        case 6:
            day = "六";
            break;
    }
    return '星期'+ day;
};

"use strict";
(function () {

    //兼容性处理
    var resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
    var _fn =  function resize() {

        var _rsd = window.Rsd||Rsd||{};
        if(_rsd.events && _rsd.events.fire)
        {
            _rsd.events.fire(null,resizeEvt,arguments);
        }
        
    };


    if (window && window.addEventListener) {
        window.addEventListener(resizeEvt, _fn, false);
    }

    //初始化
    window.Rsd = window.Rsd||{};
     
    if(window.Rsd.apply==undefined)
    {
        window.Rsd.apply = function apply(obj,config){
            var _obj = obj||{};
            var _config = config||{};
            for (var i in _config) {
                _obj[i] = _config[i];
            }
            return _obj;
        };
    }
    if (document && document.addEventListener) {
        document.addEventListener("DOMContentLoaded", function () {
            var _rsd = window.Rsd||{};
            _rsd.__readyTime = new Date().getTime();
        }, false);
    }

    if (document.currentScript) {
        var scriptArgs = document.currentScript; 
        window.Rsd.projectId = scriptArgs.getAttribute('appId') || 'TS-' + Rsd.timestamp;
        window.Rsd.projectToken = scriptArgs.getAttribute('appAuth') || 'NO Token';
    }
   
    var getUrl = function getUrl() {
        if(Rsd.__jsHomeHost)
        {
            return Rsd.__jsHomeHost;
        } 
        return document.currentScript && document.currentScript.src;
    };

    var getUrlParam = function getUrlParam(url,name) {
        
        if(typeof URL==='undefined')//URL类 仅在浏览器环境存在
        {
            return null;
        }
        var urlObj = new URL(url);
        var urlParams = urlObj.searchParams;
        var entries = urlParams&&urlParams.entries();
        if(entries===undefined)
        {
            return null;
        }
        var query = Object.fromEntries(entries); 
        return query[name];
            
    };

    var _url = getUrl()||'';
    var _host = _url.substr(0, _url.lastIndexOf('/') + 1);
    //多版本控制，v表示指定版本目录；如v=3.0.0 ,则框架加载目录为http://js.redmicro.cn/3.0.0/;不设置v 表示最新版本
    var _v = getUrlParam(_url,'v');
    if(_v)
    {
        _host = _host + _v + '/';
    }
      
    var _appConfig = null;

    if(window.Rsd.createApplication == undefined) {
        window.Rsd.createApplication = function createApplication(config) {

            _appConfig = config;
            //虚拟app，用于在应用为创建时，承接设置在app上的配置
            return _appConfig;
        }
    }
    //初始化redjs环境
    var init = function (c) {

        var _rsd = window.Rsd||{};
        delete  _rsd.onReady;
        delete  _rsd.createApplication;

        var _jsConfig = _rsd.apply({
            $className:'Rsd',
            id:'redjs',
            edition:getUrlParam(_url,'edition')||'dev',
            version: '4.0.0',
            copyright:'Nanjing Hongwei Infomation Technology Co.,LTD, All Rights Reserved',
            releaseTime:'2024-09-10 01:07:33',
            timestamp:new Date().getTime(),
            author: 'redmicro',
            domFlag:'redjs',
            domFlagValue:'',
            isDebug: false,
            isDemo:false,
            app: null,
            types: {},
            classes: {},
            classesCallback:{},
            xtypes: {},
            objects: {},
            services:{},
            singletons: {},
            //redjs服务器地址
            __jsHomeHost:'',
             //表示__jsHomeHost指向的redjs服务器是否代理服务器，代理服务器的求情格式为__jsHomeHost/base64(path),且需要在代理服务上 先解析path内容 
            __isAgentHost:false, 
            __readyTime:0,
            __id: 0,
            __zIndex: 9000
        },c);

        /**
         *
         *@global
         *
         * */
        window.Rsd = new Redjs(_jsConfig);      
        delete _rsd.apply;
        window.Rsd.apply(window.Rsd, _rsd);
        /*
        *
        * */
        window.Rsd.defineEventListener();
        /*
        * */
        window.Rsd.defineConsole();
      
        if(typeof Element !== 'undefined')
        {
            /*
            * */
            window.Rsd.defineClassList(Element);
                /*
            * */
            window.Rsd.defineFullScreen();
            /*
            * */
            window.Rsd.defineRem(window.Rsd.isMobile()?640:800);
        }
       

        window.$r = window.rsd = window.Rsd;
        //
        window.$class = Rsd.define;
        window.$lang = Rsd.l = Rsd.lang;
        window.$blank = Rsd.blankspace = Rsd.blankspan;
        window.$new = Rsd.c = Rsd.create ;
        window.$popup = Rsd.popup=Rsd.showPopup;
        window.$msg = Rsd.msg=Rsd.showMessage;
        window.$yesOrNo = Rsd.yesOrNo;
        window.$btn = Rsd.btn = Rsd.button;
        window.$txt = Rsd.txt = Rsd.text;
        window.$br = Rsd.br = Rsd.newLine;
        window.$empty = Rsd.isEmpty;
        window.$app = Rsd.createApplication;
        window.$RMB = window.$rmb = Rsd.formatCurrency;
        window.$request = window.$r.r = Rsd.$request = Rsd.req = Rsd.requestServicePromise;

        if(_appConfig != null)
        {
            window.$app(_appConfig);
        }

        //console.debug(Date.now(),'redjs initialed');
    };

    var _fn = function () {};

    //redjs 全局事件处理
    var _sys_event = function () {
        
        if(typeof Element === 'undefined')
        {
            return;
        }
        var me = Rsd;
        //延时 注册全局事件，确保document.body 对象存在
        setTimeout(function(){
            //console.debug(Date.now(),'redjs _sys_event',document && document.body);
            if(document && document.body)
                {
                    //console.debug(Date.now(),'redjs onkeydown');
                    document.body.onkeydown = function (event) {
        
                        if (event.code == 'Enter') {
        
                        }
                        if (event.code == 'Escape') {
                            Rsd.events.fire(document.body,'click',[event]);
        
                        }
                        if (event.code == 'ArrowUp') {
        
                        }
                        if (event.code == 'ArrowDown') {
        
                        }
        
                        var _key = '';
                        if (event.altKey) {
                            _key = 'alt';
                        }
                        if (event.shiftKey) {
                            _key = 'shift';
                        }
                        if (event.ctrlKey) {
                            _key = 'ctrl';
                        }
                        if (me.isEmpty(_key)) {
                            me.exeHotKeyFun(event.code);
                        } else {
                            me.exeHotKeyFun(_key + '+' + event.code);
                        }
                    };
                    //console.debug(Date.now(),'redjs onclick');
                    document.body.onclick = function (evt) {
        
                        if (evt.isCancel) {
                            return;
                        }
                        //console.log('on click....',evt.target);
                        Rsd.events.fire(document.body,'click',[evt]);
        
                    };
            }
        },100);
        
 
    };

    //加载 redjs  并启动 app
    if(window && window.Config && window.Redjs) {
        //redjs 压缩打包后 处理方式
         //加载 jquery
        var _c = new Config();
        _c.timestamp = new Date(Date.parse(_c.releaseTime.replace(/-/g,"/"))).getTime();
        init(_c);
        var me = Rsd;
 
         _fn = function __loadRedjsGblEvent( ) {
             _sys_event();
        }

    }
    else 
    {
        //redjs 动态加载时 处理方式

         //加载config,redjs 和  jquery
        var loadRedjsFile = function loadRedjsFile(url, isAsync,callback) {

            var _new_url = (_host || '') + url;
            // 创建ajax对象
            var xhr = null;
            if (window && window.XMLHttpRequest) {
                xhr = new XMLHttpRequest();
            } 
            if(xhr == null &&  typeof ActiveXObject !=='undefined') {
                xhr = new ActiveXObject('Microsoft.XMLHTTP')
            }
            if(xhr==null)
            {
                return;
            }
            if (window && Rsd.__isAgentHost) {
                var _code = window.atob && window.btoa(unescape(encodeURIComponent(url)));
                _new_url = Rsd.__jsHomeHost + _code;
            }
            //console.debug(_new_url);
            xhr.open('GET', _new_url, isAsync);//true表示异步，false表示同步
            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");//标识为ajax请求
            //xhr.setRequestHeader("Content-type", 'application/x-javascript; charset=utf-8'); // 开启后会出现 OPTIONS 请求
            xhr.send(null);
            //处理返回数据
            var _on_resp = function _on_resp()
            {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        var str = xhr.responseText;

                        try {

                            window["eval"].call(window, str);

                        } catch (e) {
                            console.error('load javascript file [' + _new_url + '] successed,execute script error in function loadRedjsFile.');
                            console.error(e);
                        }

                        if (callback) {
                            callback.call();
                        }

                    } else {
                        console.error('Failed to load resource: ' + _new_url + '(' + xhr.status + ")");
                    }
                }
            }
           
            if(isAsync)
            {
                //异步请求返回处理
                xhr.onreadystatechange = function () {  _on_resp();  };
            }
            else
            {
                //同步请求返回处理
                _on_resp();
            }
            
        };
       

         _fn = function __loadRedjsEnviroment() {

            //console.debug(Date.now(),'redjs start load...');
            
            loadRedjsFile('config.js' + '?t=' + Date.now(), false,function () {

                var _c = new Config();
                _c.timestamp = new Date(Date.parse(_c.releaseTime.replace(/-/g, "/"))).getTime();
                var _redjsUrl = 'Redjs.js' + '?t=' + _c.timestamp;

                loadRedjsFile(_redjsUrl, false,function () {

                    //console.debug(Date.now(),'redjs loaded');

                    init(_c);
                 
                    _sys_event();
                  
                });
            });
        };
    }

    _fn();
    //注册一个DOMContentLoaded事件
    if (document && document.addEventListener) 
    {
           //console.debug(Date.now(),'add event DOMContentLoaded');
           document.addEventListener("DOMContentLoaded", function(){
                //console.debug(Date.now(),'on event DOMContentLoaded');
                //_fn();
            } , false);
    }

})();



"use strict";
(function () {
 
    if( window.Rsd.Logger)
    {
        window.Rsd.Logger.info('Licence',{projectId: window.Rsd.projectId,token: window.Rsd.projectToken});
        window.Rsd.Logger.send('Redjs');
    }

})();



